package com.linq.cool.gateway.config.captcha;

import com.linq.cool.common.core.exception.UtilException;
import com.linq.cool.common.core.utils.StringUtils;
import com.wf.captcha.*;
import com.wf.captcha.base.Captcha;
import lombok.Data;
import lombok.experimental.Accessors;

import java.awt.*;
import java.util.Objects;

/**
 * @Author: yqlin
 * @Date: 2021/1/21 03:48
 * @Description:
 * @Version: 1.0.0
 */
@Data
@Accessors(chain = true)
public class CaptchaProperties {

    private CaptchaCode captchaCode;


    /**
     * 获取验证码生产类
     *
     * @return /
     */
    public Captcha getCaptcha() {
        if (Objects.isNull(captchaCode)) {
            captchaCode = new CaptchaCode();
            if (Objects.isNull(captchaCode.getCodeType())) {
                captchaCode.setCodeType(CaptchaCode.LoginCodeEnum.arithmetic);
            }
        }
        return switchCaptcha(captchaCode);
    }

    /**
     * 依据配置信息生产验证码
     *
     * @param captchaCode 验证码配置信息
     *
     * @return /
     */
    private Captcha switchCaptcha(CaptchaCode captchaCode) {
        Captcha captcha;
        synchronized (this) {
            switch (captchaCode.getCodeType()) {
                case arithmetic:
                    // 算术类型 https://gitee.com/whvse/EasyCaptcha
                    captcha = new ArithmeticCaptcha(captchaCode.getWidth(), captchaCode.getHeight());
                    // 几位数运算，默认是两位
                    captcha.setLen(captchaCode.getLength());
                    break;
                case chinese:
                    captcha = new ChineseCaptcha(captchaCode.getWidth(), captchaCode.getHeight());
                    captcha.setLen(captchaCode.getLength());
                    break;
                case chinese_gif:
                    captcha = new ChineseGifCaptcha(captchaCode.getWidth(), captchaCode.getHeight());
                    captcha.setLen(captchaCode.getLength());
                    break;
                case gif:
                    captcha = new GifCaptcha(captchaCode.getWidth(), captchaCode.getHeight());
                    captcha.setLen(captchaCode.getLength());
                    break;
                case spec:
                    captcha = new SpecCaptcha(captchaCode.getWidth(), captchaCode.getHeight());
                    captcha.setLen(captchaCode.getLength());
                    break;
                default:
                    throw new UtilException("验证码配置信息错误");
            }
        }
        if (StringUtils.isNotBlank(captchaCode.getFontName())) {
            captcha.setFont(new Font(captchaCode.getFontName(), Font.PLAIN, captchaCode.getFontSize()));
        }
        return captcha;
    }

}
